package com.jxj.study.util;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.IOException;

public class PdfEvent extends PdfPageEventHelper {

    /**
     * 创建页面时调用
     */
    @Override
    public void onStartPage(PdfWriter writer, Document document){
//        PdfContentByte con = writer.getDirectContentUnder();
//        try {
//            Image img = Image.getInstance(new URL("file:///C:/Users/admin/Desktop/图片/timg.png"));
//            img.setAlignment(Image.MIDDLE | Image.UNDERLYING);
//            img.setAbsolutePosition(0, 0);
//            img.scaleAbsolute(595, 842);
////            document.add(img);
//            con.addImage(img);
//            con.stroke();
//        } catch (IOException | DocumentException ignored) {
//        }
        PdfGState gs = new PdfGState();
        // 设置透明度为0.4
        gs.setFillOpacity(0.3f);
        gs.setStrokeOpacity(0.3f);
        try {
            PdfContentByte content = writer.getDirectContent();
            Rectangle pageSize = writer.getPageSize();
            float x = pageSize.getWidth() / 3;
            float y = pageSize.getHeight() / 3;
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            content.saveState();
            // set Transparency
            content.setGState(gs);
            content.beginText();
            content.setColorFill(BaseColor.GRAY);
            content.setFontAndSize(base, 20);
            // 水印文字成45度角倾斜
            content.showTextAligned(Element.ALIGN_CENTER, "我都水印", x, y,45);
            content.showTextAligned(Element.ALIGN_CENTER, "我都水印", x*2, y,45);
            content.showTextAligned(Element.ALIGN_CENTER, "我都水印", x, 2*y,45);
            content.showTextAligned(Element.ALIGN_CENTER, "我都水印", 2*x, 2*y,45);
            content.endText();
            content.restoreState();
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
    }
}
